package com.cn.zpark.utils;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @PackageName: com.cn.zpark.utils
 * @ClassName: DBCPUtils
 * @Description:连接池工具类
 * @author: RZS
 * @date: 2022/3/31  15:13
 */
public class DBCPUtils {
    // 定义数据库连接池信息
    //private static BasicDataSource dataSource;
    private static DataSource dataSource;

    // 初始化数据源
    static {
        // 创建properties工具类
        Properties p = new Properties();
        // 加载配置文件流对象
        InputStream ins = DBCPUtils.class.getClassLoader().getResourceAsStream("./dbcp.properties");

        try {
            // 加载配置文件
            p.load(ins);

            // 配置数据源
            dataSource = BasicDataSourceFactory.createDataSource(p);
            /*dataSource.setDriverClassName(p.getProperty("driverClassName"));
            dataSource.setUrl(p.getProperty("url"));
            dataSource.setUsername(p.getProperty("username"));
            dataSource.setPassword(p.getProperty("password"));*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        return dataSource.getConnection();
    }

    /**
     *  关闭连接
     * @param res
     * @param stat
     * @param conn
     */
    public static void close(ResultSet res, Statement stat, Connection conn){
        try {
            if(res != null){
                res.close();
            }
            if(stat != null){
                stat.close();
            }
            if(conn != null){
                conn.close();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
